/**
 * upload data mixin
 * @author Jinhui Hou
 */
import { Vue } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
import { importData } from '@/api/data-list'
import { getLocalStorage, setLocalStorage } from '@/util/util'
import { addLayerApi } from '@/api/gis'

export default class UploadDataMixin extends Vue {
  public fileList: any = []

  // 当前选择的分类
  public selectedCategoryId: number | null = null
  // 大文件上传
  public uploadingState: string = 'success' // 加载状态
  public loadingProgress: number = 0 // 加载进度
  public loadingText: string = '导入中' // 加载文本

  public isUploading: boolean = false // 文件是否正在上传

  public fileType: string = '' // 文件类型

  public fileCodingType: string = 'utf-8' // 文件编码
  // 导入数据编码方式
  public datasetCodingType: Array<string> = [
    'utf-8',
    'ASCII',
    'GB18030',
    'Unicode',
  ]

  // 可选的目录
  public get categoryOptions(): { categoryId: number; categoryName: string }[] {
    if (DataStore.datasetCategory) {
      return DataStore.datasetCategory.map((d) => {
        return {
          categoryId: d.categoryId,
          categoryName: d.categoryName,
        }
      })
    }
    return []
  }

  /**
   * select-option里的项 TODO 修改
   */
  public get categorySelectOptions() {
    const result: any[] = [...this.categoryOptions].reverse() as any[]
    // 自动赋值
    if (!this.selectedCategoryId) {
      const storageSelectedCategoryId = Number(
        getLocalStorage('selectedCategoryId')
      )
      if (storageSelectedCategoryId) {
        this.selectedCategoryId = storageSelectedCategoryId
      }
    }
    const datasetCategoryOptionsHasSelectedCategory: boolean = result.some(
      (item: any) => item.categoryId === this.selectedCategoryId
    )
    if (result.length > 0 && !datasetCategoryOptionsHasSelectedCategory) {
      this.selectedCategoryId = result[0].categoryId
    }
    return result
  }

  /**
   * 表单中文件夹选项选中项出现变化时，同步到LocalStorage对应项中
   */
  public async selectedCategoryIdChanged(newCategoryId: number) {
    setLocalStorage('selectedCategoryId', String(newCategoryId))
  }

  /**
   * 只能上传一个文件，重复上传会覆盖
   */
  public async handleUploadMixin(info: any) {
    this.fileList = [...info.fileList].slice(-1)
    if (info.fileList.length === 0) {
      this.fileType = ''
    } else {
      // 获取类型
      this.fileType = this.fileList[0].name.slice(
        this.fileList[0].name.lastIndexOf('.') + 1
      )
    }
  }

  /**
   * 上传前限制文件大小
   */
  public beforeUpload(file: any) {
    const [, fileType] = file.name.toString().split('.')
    let fileSizeAvailiable: boolean
    // 如果为csv文件，限制大小为20G
    if (fileType === 'csv') {
      fileSizeAvailiable = file.size / 1024 / 1024 / 1024 / 20 < 1
      if (!fileSizeAvailiable) {
        this.$message.error('超过文件大小限制（20GB）!')
      }
    } else {
      fileSizeAvailiable = file.size / 1024 / 1024 / 1024 < 1
      if (!fileSizeAvailiable) {
        this.$message.error('超过文件大小限制（1GB）!')
      }
    }
    return fileSizeAvailiable
  }

  /**
   * 回到之前跳转到这个数据导入的页面，数据视图加载数据/图分析加载数据
   */
  public async goBackPreView(selectedDataType: string, datasetIds: any = [-1]) {
    let lastUrl: any = sessionStorage.getItem('lastUrl')
    if (lastUrl) {
      lastUrl = JSON.parse(lastUrl)
      console.log(lastUrl)
      const { href } = this.$router.resolve({
        path: lastUrl.url,
      })
      const { projectId, loadType, tabId } = lastUrl
      // 如果是表格数据
      if (selectedDataType === 'table' || selectedDataType === 'http') {
        if (loadType === 'table') {
          const data = { projectId, datasetIds: [...datasetIds] }
          await importData({ data })
        }
      } else if (selectedDataType === 'gis') {
        await addLayerApi({
          data: { projectId, tabId, datasetIds: [...datasetIds] },
        })
      }
      sessionStorage.removeItem('lastUrl')
      window.location.href = href
      console.log(href)
    } else {
      await this.$router.push('/management/data')
    }
  }
}
